package com.huajiao.management_system.util;

import com.huajiao.management_system.bean.prove;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * 上传工具
 */
public class UploadUtil {
    /**
     * 存储路径
     */
//    private final static String FILE_UPLOAD_DIC = "C:/Users/99275/IdeaProjects/management_system/src/main/resources/static/";
    private final static String FILE_UPLOAD_DIC = System.getProperty("user.dir");
    public static List<prove> upload(MultipartFile[ ] files, String typeName, String resName, Integer resId, Integer typeId){
        List<prove> list = new LinkedList<>();
        String path = FILE_UPLOAD_DIC+"/image/"+typeName;
        File fileDirectory = new File(path);
        try{
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
            }
        }
        for (int i = 0;i<files.length;i++) {
            String fileName = files[i].getOriginalFilename();
            if ("".equals(fileName)){
               break;
            }
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //生成文件名称通用方法
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            Random r = new Random();
            StringBuilder tempName = new StringBuilder();
            tempName.append(resName+sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
            String newFileName = tempName.toString();

            //创建文件
            File destFile = new File(path + "/" + newFileName);

            files[i].transferTo(destFile);
            prove prove = new prove();
            prove.setProveUrl(System.getProperty("user.dir") + "/image/"+typeName+"/"+newFileName);
            prove.setResId(resId);
            prove.setResName(resName);
            prove.setTypeId(typeId);
            list.add(prove);
        }
            } catch (IOException e){
                e.printStackTrace();
            }
        return list;
    }
}
